% LocalMaxStats - Local Maximum Statistics for an image.
%
% USAGE:
% avg = LocalMaxStats(img)
%
% INPUTS:
% img - an image matrix
%
% OUTPUTS:
% avg - the average of the local maximum values in the image (with the
%       global maximum excluded). A pixel is considered a local maximum if
%       its values exceeds all eight of its immediate neighbors.
%
function [avg, lm_count] = LocalMaxStats(img)
    [r c] = size(img);
    rrng = 2:(r-1); %borders are masked in HRL code
    crng = 2:(c-1);
    center = img(rrng, crng);
    extreme = max(center(:));
    offset = [-1 -1; -1 0; -1 1; 0 -1; 0 1; 1 -1; 1 0; 1 1];
    count = zeros(size(img,1)-2, size(img,2)-2);
    for ix = 1:8
        nbr = img(rrng+offset(ix,1), crng+offset(ix,2));    % Modified to NOT necessarily have unique local max in the window
        count = count + (center >= nbr);                    % (>= instead of >)
    end
    locMax = find(count > 7);
    if length(locMax) < 2;
        avg = 0;
        return
    end
     
    lm_count = length(locMax) - 1;
    avg = (sum(center(locMax)) - extreme) / (length(locMax) - 1);
    if(isinf(avg)) 
        error('no local max');
    end
        





